package com.example.datadictionary.service;

import com.example.datadictionary.model.TableInfo;
import com.example.datadictionary.model.ColumnInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class DatabaseService {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    // 查询所有表名和表备注
    public List<TableInfo> getTableInfo() {
        String sql = "SELECT TABLE_NAME AS tableName, TABLE_COMMENT AS tableComment " +
                "FROM information_schema.TABLES " +
                "WHERE TABLE_SCHEMA = DATABASE()";
        return jdbcTemplate.query(sql, (rs, rowNum) -> {
            TableInfo tableInfo = new TableInfo();
            tableInfo.setTableName(rs.getString("tableName"));
            tableInfo.setTableComment(rs.getString("tableComment"));
            return tableInfo;
        });
    }

    // 查询指定表的字段信息
    public List<ColumnInfo> getColumnInfo(String tableName) {
        String sql = "SELECT COLUMN_NAME AS columnName, COLUMN_TYPE AS columnType, COLUMN_COMMENT AS columnComment, " +
                "COLUMN_DEFAULT AS defaultValue, IS_NULLABLE AS isNullable " +
                "FROM information_schema.COLUMNS " +
                "WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ?";;
        return jdbcTemplate.query(sql, new Object[]{tableName}, (rs, rowNum) -> {
            ColumnInfo columnInfo = new ColumnInfo();
            columnInfo.setColumnName(rs.getString("columnName"));
            columnInfo.setColumnType(rs.getString("columnType"));
            columnInfo.setColumnComment(rs.getString("columnComment"));
            columnInfo.setDefaultValue(rs.getString("defaultValue"));
            columnInfo.setIsNullable(rs.getString("isNullable"));
            return columnInfo;
        });
    }
}